package javacommon.authority.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
/**
 * 用户AR
 * @author zhengwei
 *
 */
public class User extends Model<User>{
	public static final User dao = new User();
	
	public Page<User> findByPage(Integer pageIndex) {
		String select = "select *";
		String sqlExceptSelect = "from t_user";
		Page<User> page = dao.paginate(pageIndex==null?1:pageIndex, 10, select, sqlExceptSelect);
		return page;
	}
	public List<UserRole> getRoles(){
		return UserRole.dao.find("select * from t_user_role where userId=?",get("id"));
	}
	public List<UserOrg> getOrgs(){
		return UserOrg.dao.find("select * from t_user_org where userId=?",get("id"));
	}
	/**
	 * 递归产生树型菜单
	 * @return
	 */
	public List<Menu> getMenuAndLeaf() {
		List<Menu> list=getMenus(1);
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		List<Menu> wrapList=new ArrayList<Menu>();
		diguiwrapList(list, wrapList, null);
		
		return wrapList;
	}

	/**
	 * 获得当前用户的菜单
	 * @param menutype 菜单类型 1为导航菜单
	 * @return
	 */
	public List<Menu> getMenus(Integer menutype) {
		String sql = "SELECT m.* from t_menu m,t_role_menu  rm,t_user_role  ur "
				+ "where ur.userId=? and ur.roleId=rm.roleId and m.id=rm.menuId  "
				+ "and m.state=?";
		String userId=get("id");
		if (menutype != null) {
			sql+=" and m.type=? order by m.sort asc";
			return Menu.dao.find(sql, userId,"是",menutype);
		}else {
			sql+= " order by m.sort asc ";
			return Menu.dao.find(sql, userId,"是");
		}
	}
	private List<Menu> diguiwrapList(List<Menu> from,List<Menu> tolist,String parentId) {

		if(CollectionUtils.isEmpty(from)){
			return null;
		}
		
		for(int i=0;i<from.size();i++){
			Menu m=from.get(i);
			if(m==null||(m.getInt("type")-0==0)){
				//from.remove(i);
			//	i=i-1;
				continue;
			}
		
			String pid=m.getStr("pid");
			if((pid==null)&&(parentId!=null)){
				continue;
			}
		
			if((parentId==m.getStr("pid"))||(m.getStr("pid").equals(parentId))){
				List<Menu> leaf=new ArrayList<Menu>();
				m.put("leaf", leaf);
				tolist.add(m);
				//from.remove(i);
			//	i=i-1;
			  diguiwrapList(from, leaf, m.getStr("id"));
				if(CollectionUtils.isEmpty(leaf)){
					continue;
				}
			}
		}
		
		return tolist;
		
	}
	public User findFirstByAccount(String account) {
		return dao.findFirst(
				"select * from t_user where account=?", account);
	}
}
